package com.qqt.csr.im.socketio.channel;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

@Slf4j
@ChannelHandler.Sharable
public class HttpHealthyUrlHandler extends ChannelInboundHandlerAdapter {
    private final static String STATUS_UP = "{\"status\":\"UP\"}";
    private final static String PATH = "/actuator/health";

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest req) {
            QueryStringDecoder queryDecoder = new QueryStringDecoder(req.uri());
            if (queryDecoder.path().contains(PATH)) {
                HttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK, Unpooled.copiedBuffer(STATUS_UP, CharsetUtil.UTF_8));
                ctx.channel().writeAndFlush(res).addListener(ChannelFutureListener.CLOSE);
                req.release();
                return;
            }
        }
        super.channelRead(ctx, msg);
    }
}
